<template>
  <div class="test">
    <van-nav-bar title="登录" left-arrow @click-left="onClickLeft" />
    <!-- 校验通过之后，我们才会执行submit自定义事件对应的函数 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="loginname"
        name="手机号"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号不合法!'
          }
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '请填写密码' },
          {
            pattern: /^\w{6,16}$/,
            message: '密码必须是6-16位'
          }
        ]"
      />
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { login } from '@/api/user'
import { mapMutations } from 'vuex'
import { Toast } from 'vant'
export default {
  data () {
    return {
      loginname: '17704051019',
      password: '123456'
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    onClickLeft () {
      this.$router.back()
    },
    async onSubmit () {
      try {
        const res = await login({
          loginname: this.loginname,
          password: this.password
        })

        if (res.code === 200) {
          // 保存token 到仓库中
          this.setToken(res.data.token)

          // 提示
          Toast({
            duration: 800,
            type: 'success',
            message: res.message,
            onClose: () => {
              if (this.$route.query.redirect) {
                // 跳转到layout
                this.$router.push(this.$route.query.redirect)
              } else {
                // 跳转到layout
                this.$router.push('/')
              }
            }
          })
        } else {
          Toast.fail(res.message)
        }
      } catch (error) {
        console.log('---error---', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.test {
  color: blue;
}
::v-deep(.van-nav-bar .van-icon) {
  color: #333;
}

::v-deep(.van-button--primary) {
  color: #fff;
  background-color: #c82519;
  border: 1px solid #c82519;
}
</style>
